//
//  JDMemberAreaViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/10/27.
//

import UIKit

// 这个页面还需要做的是  导航栏问题  分类按钮的问题  渐变色的问题  悬停应该不需要考虑
class JDMemberAreaViewController: JDBaseViewController {

    var tableViewHeaderView: UIView?
    var mainTableView: UITableView?
    
    var needRefreshClassification = true
    var goodsModels: [JDGoodsModel?]?
//    var gradientView: UIView?
    
    var classificationView: DraClassicHeadView?
    var goodsTypeTitleList: [String] = ["全部"]
    var goodsTypeModels :[JDGoodsTypeModel?]?
    // 选中的分类的code
    var categoryCode = ""
    
    var customTitleLabel: UILabel?
    var backButton: UIButton?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupUIElements()
        self.getClassificationData()
        self.getNetData()
        self.setupConfig()
        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.changeCustomNavigationBarAlpha(0.0)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.changeCustomNavigationBarAlpha(0.0)
    }
    
    func setupConfig() {
        
        self.splitSubviewNavigationbar("black_back", #selector(backAction), self, "会员专区")
//        self.setupLeftBackItem()
        self.changeCustomNavigationBarAlpha(0.0)
        
//        self.backButton = UIButton(type: .custom)
//        self.view.addSubview(self.backButton!)
//        self.backButton?.snp.makeConstraints { make in
//            make.left.equalTo(self.view)
//            make.top.equalTo(self.view).offset(UIDevice().safeAreaInset.top-44)
//            make.size.equalTo(CGSizeMake(44, 44))
//        }
//        self.backButton?.setImage(UIImage(named: "black_back")?.withRenderingMode(.alwaysOriginal), for: .normal)
//        self.backButton?.addTarget(self, action: #selector(backAction), for: .touchUpInside)
//        
//        self.customTitleLabel = UILabel()
//        self.view.addSubview(self.customTitleLabel!)
//        self.customTitleLabel?.snp.makeConstraints({ make in
//            make.centerX.equalTo(self.view)
//            make.centerY.equalTo(self.backButton!)
//        })
//        self.customTitleLabel?.text = "会员专区"
    }
    
    override func backAction() {
        super.backAction()
        self.changeCustomNavigationBarAlpha(1)
    }
    
    func setupUIElements() {
        
        self.mainTableView = UITableView(frame: .zero, style: .plain)
        self.mainTableView?.contentInsetAdjustmentBehavior = .never
        if #available(iOS 15.0, *) {
            self.mainTableView?.sectionHeaderTopPadding = 0.0
        } else {
            // Fallback on earlier versions
        }
        
        self.view.addSubview(self.mainTableView!)
        self.mainTableView?.snp.makeConstraints({ make in
            make.leading.trailing.top.bottom.equalTo(self.view)
        })
//        self.mainTableView?.tableHeaderView = self.createHeaderView()
        self.mainTableView?.delegate = self
        self.mainTableView?.dataSource = self
        self.mainTableView?.register(JDGoodsListCell.self, forCellReuseIdentifier: "mainTableViewCell")
//        self.mainTableView?.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "headerView")
        self.mainTableView?.separatorStyle = .none
        
        self.mainTableView?.contentInset = UIEdgeInsets(top: 268+59, left: 0, bottom: 0, right: 0)
        let headerView = self.createHeaderView()
        self.mainTableView?.addSubview(headerView)
        
        let sectionHeaderView = self.sectionHeaderView()
        self.mainTableView?.addSubview(sectionHeaderView)
        
//        self.mainTableView?.addGradient(with: [UIColor.white.cgColor, color("#F5F6F8").cgColor], frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: 200-59))
//        self.mainTableView?.bringSubviewToFront(self.classificationView!)
        
//
        
//        self.mainTableView?.backgroundColor = .verticalGradientColor(topColor: .red, bottomColor: color("#F5F6F8"), colorFrame: CGRectMake(0, 0, screenWidth, 240))
//        
//        
//        self.gradientView = UIView()
//        self.mainTableView?.addSubview(self.gradientView!)
//        self.gradientView?.snp.makeConstraints({ make in
//            make.leading.trailing.equalTo(self.view)
//            make.top.equalTo(self.mainTableView!)//.offset(268)
//            make.height.equalTo(240)
//        })
//        self.gradientView?.backgroundColor = .verticalGradientColor(topColor: .white, bottomColor: color("#F5F6F8"), colorFrame: CGRectMake(0, 0, screenWidth, 240))
        
//        let gradientView = UIView()
//        gradientView.frame = CGRectMake(0, 268, screenWidth, 240)
//        self.mainTableView?.addSubview(gradientView)
//        gradientView.backgroundColor = .verticalGradientColor(topColor: .red, bottomColor: color("#F5F6F8"), colorFrame: CGRectMake(0, 0, screenWidth, 240))
//        self.mainTableView?.layer.addSublayer(gradientView.layer)
////        self.mainTableView?.sendSubviewToBack(gradientView)
//        
        
        
//        self.view.bringSubviewToFront(self.backButton!)
//        self.view.bringSubviewToFront(self.customTitleLabel!)
        
        
        self.mainTableView?.addRefreshHeader(ignoredTopInset: 268+59, { [weak self] in
            if self?.needRefreshClassification ?? true {
                self?.getClassificationData()
            }
            self?.currentPage = 1
            self?.getNetData(true)
            
        })
        
        self.mainTableView?.addRefreshFooter { [weak self] in
            self?.currentPage += 1
            self?.getNetData(false)
        }
        
        self.setupTableViewEmptyView(self.mainTableView, offsetY: -110)
        
    }
    
    func createHeaderView() -> UIView {

        let headerView = UIView()
        headerView.frame = CGRectMake(0, -268-59, screenWidth, 268)
        headerView.backgroundColor = .red
        
        let bgImgV = UIImageView()
        headerView.addSubview(bgImgV)
        bgImgV.snp.makeConstraints { make in
            make.leading.trailing.top.bottom.equalTo(headerView)
        }
        bgImgV.image = UIImage(named: "memberAreaBgView")?.withRenderingMode(.alwaysOriginal)
        
        
        let whiteBgView = UIView()
        headerView.addSubview(whiteBgView)
        whiteBgView.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalTo(headerView)
            make.height.equalTo(8)
        }
        whiteBgView.layer.cornerRadius = 8
        whiteBgView.layer.maskedCorners = [.layerMinXMinYCorner,.layerMaxXMinYCorner]
        whiteBgView.backgroundColor = .white
        
        let moreDetailButton = UIButton(type: .custom)
        headerView.addSubview(moreDetailButton)
        moreDetailButton.snp.makeConstraints { make in
            make.trailing.equalTo(headerView).offset(-20)
            make.bottom.equalTo(headerView).offset(-8)
            make.height.equalTo(42)
            make.width.equalTo(70)
        }
        moreDetailButton.addTarget(self, action: #selector(memberDetailInfo), for: .touchUpInside)
        
        return headerView
    }
    
    func sectionHeaderView() -> UIView {
        
//        let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "headerView")
//        headerView?.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 59)
        
        let headerView = UIView(frame: CGRect(x: 0, y: -59, width: screenWidth, height: 59))
        
        let moreButton = UIButton(type: .custom)
        headerView.addSubview(moreButton)
        moreButton.snp.makeConstraints { make in
            make.trailing.equalTo(headerView).offset(-10)
            make.top.equalTo(headerView).offset(11+5)
            make.size.equalTo(CGSizeMake(46, 28))
        }
        moreButton.setTitle("分类", for: .normal)
        moreButton.setImage(UIImage(named: "arrow_black"), for: .normal)
        
        moreButton.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .regular)
        moreButton.setTitleColor(color("#333333"), for: .normal)
        moreButton.semanticContentAttribute = .forceRightToLeft
        moreButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 4)
        moreButton.addTarget(self, action: #selector(moreButtonAction), for: .touchUpInside)
        if self.classificationView == nil {
            self.classificationView = DraClassicHeadView.init(CGRect(x: 0, y: 0, width: screenWidth-56, height: 44), titles: self.goodsTypeTitleList, index: 0)
            self.classificationView?.backgroundColor = .clear
            self.classificationView?.delegate = self
            
            self.goodsTypeTitleList = ["全部"]
            for typeModel in self.goodsTypeModels ?? [JDGoodsTypeModel?]() {
                self.goodsTypeTitleList.append(typeModel?.name ?? "异常")
            }
            DispatchQueue.main.asyncAfter(deadline: .now()+0.2) {
                self.classificationView?.updateData(self.goodsTypeTitleList, index: 0)
            }
        }
        headerView.addSubview(self.classificationView!)
        self.classificationView?.snp.removeConstraints()
        self.classificationView?.snp.makeConstraints({ make in
            make.leading.equalTo(headerView)
            make.trailing.equalTo(moreButton.snp.leading)
            make.top.equalTo(headerView).offset(8-3)
            make.height.equalTo(44)
        })
        headerView.backgroundColor = .white
        
//        headerView?.backgroundColor = .orange
//        headerView?.contentView.backgroundColor = .green
        return headerView
    }
    
    
    
    
    @objc func memberDetailInfo() {
        self.view.toast(message: "了解详情")
        let memberDescriptionVC = JDMemberDescriptionViewController()
        self.hidesBottomBarPushViewController(memberDescriptionVC)
    }
    

    @objc func getClassificationData() {
        
        JDNetWorkRequest(.getGoodsType([:])) { responseStr in
            
            printLog("分类信息:\(responseStr)")
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                
                if let models = [JDGoodsTypeModel].deserialize(from: responseStr, designatedPath: "data") {
                    self.needRefreshClassification = false
                    self.goodsTypeModels = models
                    self.goodsTypeTitleList = ["全部"]
                    for typeModel in models {
                        self.goodsTypeTitleList.append(typeModel?.name ?? "异常")
                    }
                    self.categoryCode = models.first??.pid ?? ""
                    DispatchQueue.main.asyncAfter(deadline: .now()+0.2) {
                        self.classificationView?.updateData(self.goodsTypeTitleList, index: 0)
                    }
                }
            }
            
        } failure: { error in
            
        } error: { errorCode in
            
        }
    }
    
    override func getNetData(_ isRefresh: Bool = true) {
        
        var params = [String: Any]()
        // 国家代码
        params["countryCode"] = "all"
        // 商品分类 -- 这个还要改
        if self.categoryCode.count > 0 {
            params["goodsCategory"] = self.categoryCode
        }
        params["pageNumber"] = self.currentPage
        params["pageSize"] = 10
        params["goodsMemberLevel"] = 2
        
        self.showLoading()
        JDNetWorkRequest(.getGoodsList(params)) { responseStr in
            self.dismissLoading()
            printLog("商品列表信息:\(responseStr)")
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                
                if let models = [JDGoodsModel].deserialize(from: responseStr, designatedPath: "data.records") {
                    
                    if isRefresh {
                        self.goodsModels = models
                    } else {
                        self.goodsModels?.append(contentsOf: models)
                    }
                    
                    if models.count < 10 {
                        self.mainTableView?.reloadData()
//                        self.mainTableView?.ly_endLoading()
                        self.mainTableView?.noMoreData()
                        return
                    }
                } else {
                    self.view.toast(message: "数据异常")
                }
            } else {
                self.view.toast(message: commonModel?.msg ?? "网络异常")
            }
            self.mainTableView?.reloadData()
//            self.mainTableView?.ly_endLoading()
            self.mainTableView?.endRefresh()
            
        } failure: { error in
            self.dismissLoading()
            self.view.toast(message: error.localizedDescription)
        } error: { errorCode in
            self.dismissLoading()
            self.view.toast(message: "网络异常")
        }

    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    @objc func moreButtonAction() {
        self.changeCustomNavigationBarAlpha(1)
        let classilicationVC = JDClassificationViewController()
        classilicationVC.goodsTypeModels = self.goodsTypeModels
        self.hidesBottomBarPushViewController(classilicationVC)
        classilicationVC.selectedClassificationCompleted = {[weak self] classificationIndex ,selectedId in
            guard let classificationId = selectedId else { return }
            guard let weakSelf = self else { return }
            weakSelf.classificationView?.updateData(weakSelf.goodsTypeTitleList, index: classificationIndex+1)
            weakSelf.categoryCode = classificationId
            weakSelf.currentPage = 1
            weakSelf.getNetData(true)
        }
    }

}

extension JDMemberAreaViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.goodsModels?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "mainTableViewCell") as? JDGoodsListCell
        cell?.contentView.backgroundColor = .clear
        cell?.selectionStyle = .none
        let goodsModel = self.goodsModels?[indexPath.row]
        cell?.goodsModel = goodsModel
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 97+10
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        guard let goodsModel = self.goodsModels?[indexPath.row] else {
            return
        }
        self.changeCustomNavigationBarAlpha(1)

        let goodsDetailVC = JDGoodsDetailViewController()
        goodsDetailVC.goodsLogoUrl = goodsModel.goodsMainImgUrl
        goodsDetailVC.goodsID = goodsModel.goodsId
        self.hidesBottomBarPushViewController(goodsDetailVC)
    }
    
//    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//        return 59
//    }
    
//    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//        
//        let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "headerView")
////        headerView?.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 59)
//        
//        for subV in headerView?.contentView.subviews ?? [UIView]() {
//            subV.removeFromSuperview()
//        }
//        
//        headerView?.contentView.isUserInteractionEnabled = false
//        
//        let moreButton = UIButton(type: .custom)
//        headerView?.contentView.addSubview(moreButton)
//        moreButton.snp.makeConstraints { make in
//            make.trailing.equalTo(headerView!.contentView).offset(-10)
//            make.top.equalTo(headerView!.contentView).offset(11+5)
//            make.size.equalTo(CGSizeMake(46, 28))
//        }
//        moreButton.setTitle("分类", for: .normal)
//        moreButton.setImage(UIImage(named: "arrow_black"), for: .normal)
//        
//        moreButton.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .regular)
//        moreButton.setTitleColor(color("#333333"), for: .normal)
//        moreButton.semanticContentAttribute = .forceRightToLeft
//        moreButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 4)
//        moreButton.addTarget(self, action: #selector(moreButtonAction), for: .touchUpInside)
//        if self.classificationView == nil {
//            self.classificationView = DraClassicHeadView.init(CGRect(x: 0, y: 0, width: screenWidth-56, height: 44), titles: self.goodsTypeTitleList, index: 0)
//            self.classificationView?.backgroundColor = .clear
//            self.classificationView?.delegate = self
//            
//            self.goodsTypeTitleList = ["全部"]
//            for typeModel in self.goodsTypeModels ?? [JDGoodsTypeModel?]() {
//                self.goodsTypeTitleList.append(typeModel?.name ?? "异常")
//            }
//            DispatchQueue.main.asyncAfter(deadline: .now()+0.2) {
//                self.classificationView?.updateData(self.goodsTypeTitleList, index: 0)
//            }
//        }
//        headerView?.contentView.addSubview(self.classificationView!)
//        self.classificationView?.snp.removeConstraints()
//        self.classificationView?.snp.makeConstraints({ make in
//            make.leading.equalTo(headerView!.contentView)
//            make.trailing.equalTo(moreButton.snp.leading)
//            make.top.equalTo(headerView!.contentView).offset(8-3)
//            make.height.equalTo(44)
//        })
//        
//        headerView?.backgroundColor = .orange
//        headerView?.contentView.backgroundColor = .green
//        return headerView
//    }
    
}

extension JDMemberAreaViewController: DraClassicHeadViewDelegate {
    func didSelectTitleAt(_ index: Int) {
        if index == 0 {
            self.categoryCode = ""
        } else {
            let selectedModel = self.goodsTypeModels?[index-1]
            self.categoryCode = selectedModel?.id ?? "0"
        }
        self.currentPage = 1
        self.getNetData(true)
        print("点了啊")
    }
}

extension JDMemberAreaViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let offsetY = scrollView.contentOffset.y + 327
        print("这个值:\(offsetY)")
        if offsetY > 100.0 {
            self.changeCustomNavigationBarAlpha(1)
        } else {
            let scale = offsetY/100.0
            self.changeCustomNavigationBarAlpha(scale)
        }
    }
}

